import axios from "axios";
import {ElMessage} from "element-plus";
import {ref} from "vue";

const defaultError = () => {ElMessage.error('发生了一些异常，请联系管理员')}
const defaultFailure = (data) => {ElMessage.warning(data)}

function post(url, data, success, failure = defaultFailure, error = defaultError) {
    axios.post(url, data, {
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        withCredentials: true
    }).then(({data}) => {
        if (data.success) {
            success(data.message)
        }else
            failure(data.message)
    }).catch(error)
}

function send_chat_data(url, data, callback, failure = defaultFailure, error = defaultError) {
    axios.post(url, data, {
        headers:{
            'Content-Type': 'application/json'
        },
        withCredentials: true
    }).then(({data}) => {
        callback(data)
    }).catch(error)
}

function register(url, data, success, failure = defaultFailure, error = defaultError) {
    axios.post(url, data, {
        headers:{
            'Content-Type': 'application/json'
        },
        withCredentials: true
    }).then(({data}) => {
        if (data.success) {
            success(data.message)
        }else
            failure(data.message)
    }).catch(error)
}

function get(url, success, failure = defaultFailure, error = defaultError) {
    axios.get(url, {
        withCredentials: true
    }).then(({data}) => {
        if (data.success) {
            success(data.message)
        }else
            failure(data.message)
    }).catch((e) => {
        if (e.response.data.status === 403) {
            failure('无访问权限')
        }
    })
}

export {get, post, register, send_chat_data}
